<template>
  <div class="form-container">
    <!-- 头部导航 -->
    <div class="header">
      <h2>请假申请</h2>
    </div>

    <!-- 表单主体 -->
    <!-- :model="formMsg" 与v-model的作用相同，只是绑定的是整个表单的数据     -->
    <el-form :model="formMsg" :rules="formRules" label-width="80px" label-position="left">
      <!-- 基本信息行 -->
      <div class="form-row">
        <el-form-item label="姓名">
          <el-input v-model="formMsg.name" readonly />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="formMsg.department" readonly />
        </el-form-item>
      </div>

        <!-- 请假类型 -->
        <!-- prop表示需要校验的字段       -->
      <el-form-item label="请假类型" prop="leaveType" required>
          <div class="checkbox-grid">
<!--              修改成单选框-->
              <el-radio-group v-model="formMsg.leaveType">
                  <el-radio v-for="type in leaveTypes" :label="type"/>
              </el-radio-group>

          </div>
      </el-form-item>

      <!-- 时间选择 -->
      <div class="form-row">
        <el-form-item label="开始时间" prop="startTime" required>
          <el-date-picker
              v-model="formMsg.startTime"
              type="datetime"
              placeholder="请选择日期"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" required>
          <el-date-picker
              v-model="formMsg.endTime"
              type="datetime"
              placeholder="请选择日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </div>

      <!-- 天数和事由 -->
      <div class="form-row">
        <el-form-item label="请假天数">
            <!--  最小值，最大值，步长，最多保留的小数位  -->
          <el-input-number
              v-model="formMsg.days"
              :min="1"
              :max="365"
              :step="1"
              :precision="0"
          />
        </el-form-item>
        <el-form-item label="请假事由" prop="reason" required>
          <el-input
              v-model="formMsg.reason"
              type="textarea"
              :rows="3"
              placeholder="请输入事由"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="saveDraft">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";

// 表单数据
const formMsg = ref({
    name: '张三',
    department: '产品设计部',
    startTime: '',
    endTime: '',
    days: 1,
    reason: '',
    leaveType:'',
    approvalType:'请假申请'
})

// 请假类型选项
const leaveTypes = ref([
  '事假', '病假', '年假', '调休',
  '婚假', '产假', '陪产假', '其他'
])
//开始时间不得早于当前时间
const validateStartTime = (rule, value, callback)=>{
    if(value && new Date(value) >= new Date()){
        callback();
    }else{
        formMsg.value.startTime='';
        callback(new Error('开始时间不得早于当前时间'));
    }
}
//结束时间不得早于开始时间
const validateEndTime = (rule, value, callback)=>{
    if(formMsg.value.startTime){
        if(value && new Date(value) >= new Date(formMsg.value.startTime)){
            //验证通过
            callback();
        }else{
            callback(new Error('结束时间不得早于开始时间'));
        }
    }else{
        formMsg.value.endTime='';
        callback(new Error('请先填写开始时间'));
    }
}
//定义校验规则，因为表单是使用reactive动态提交，change就会被触发
const formRules = {
    leaveType: [{ required: true, message: '请假类型是必填项', trigger: 'change' }],
    startTime: [{ required: true, message: '开始时间是必填项', trigger: 'change' },
        {validator: validateStartTime, trigger: "change"}],
    endTime: [{ required: true, message: '结束时间是必填项', trigger: 'change' },
        {validator: validateEndTime, trigger: "change"}],
    reason: [{ required: true, message: '请假事由是必填项', trigger: 'blur' }]
}
//记录是否有草稿
let isDraft = false;
// 表单提交方法
const submitForm = () => {
    formMsg.value.userId = getUser().id;
    let data = qs.stringify(formMsg.value)
    axios.post(BASE_URL + '/v1/vacate/staffLeave?'+data)
        .then((response)=>{
            if(response.data.code == 2000){
                localStorage.removeItem("leaveDraftMsg");
                localStorage.removeItem("leaveIsDraft");
                isDraft = false;
                window.history.back();
            }else {
                ElMessage.error("请假申请失败")
            }

    })
}

const saveDraft = () => {
    isDraft = true;
    localStorage.setItem("leaveDraftMsg",JSON.stringify(formMsg.value))
    localStorage.setItem("leaveIsDraft",JSON.stringify(isDraft));
    window.history.back();
}

const goBack = () => {
        window.history.back()
}


onMounted(()=>{
    //判断是否有该字段，并是否为true
    if(localStorage.getItem("leaveIsDraft")){
        formMsg.value =  JSON.parse(localStorage.leaveDraftMsg)
    }
})
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 20px;
}

.checkbox-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px 24px;
}

.action-buttons {
  margin-top: 32px;
  text-align: right;
}


:deep(.el-form-item__label)::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

:deep(.el-button.is-link) {
  color: #1a5cff;
}
</style>